<template>
	<div class="container">
		<el-container>
			<el-header style="width: 40%">
				<el-card shadow="hover" style="height: 100px">
					<el-form-item label="目标终端">
						<el-cascader placeholder="设备ID"
												 :options="options"
												 :props="props"
												 filterable
												 :show-all-levels="false"
												 collapse-tags
												 @change="getDevice"
						/>
					</el-form-item>
				</el-card>
			</el-header>
			<el-aside width="45%">
				<el-card shadow="hover" style="height: 643px; width: 83%; margin-left: 20px; margin-top: 75px">
					<img :src="pictureUrl" style="width: 350px;margin-top: 15%; margin-left: 15%">
					<el-form-item label="当前操作设备">
						<el-input v-model="deviceValue" disabled></el-input>
					</el-form-item>
					<el-form-item style="margin-left: 36%;margin-top: 10%">
						<el-tag>开关
							<el-icon size="large" style="position: relative; top: 4px"><SwitchButton/></el-icon>
						</el-tag>
						<el-switch v-model="switchState" @change="controlSwitch(switchState)" size="large" style="margin-left:10px" :disabled="lightDisabled">
							<template #active-action>
								<span class="el-icon-third el-third-iconkaidengmianxing"></span>
							</template>
							<template #inactive-action>
								<span class="el-icon-third el-third-iconguandengmianxing"></span>
							</template>
						</el-switch>
					</el-form-item>
				</el-card>
			</el-aside>
			<el-main style="width: 63%;position: absolute;top: 47px;right: 25px">
				<el-card shadow="hover" style="margin-left: 65px; margin-top: 5px; width: 950px; height: 248px">
					<el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick" style="padding-left: 15px; position: relative;right: 2%">
						<el-tab-pane label="系统模式" name="first">
							<el-scrollbar height="160px">
								<p v-for="item in systemLight" :key="item" class="scrollbar-demo-item">
									<el-tag style="width: 80px">{{item.mode}}</el-tag>
									<el-switch
											v-model="item.state"
											class="ml-2"
											style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949; margin-left: 20px"
											@change="checkModeState(item)"
											:disabled="systemModeDisabled"
									/>
								</p>
							</el-scrollbar>
							</el-tab-pane>
						<el-tab-pane label="自定义模式" name="fourth">
							<el-scrollbar height="160px">
								<p v-for="item in autoLight" :key="item" class="scrollbar-demo-item">
									<el-tag style="width: 80px">{{item.mode}}</el-tag>
									<el-switch
											v-model="item.state"
											class="ml-2"
											style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949; margin-left: 20px"
											@change="checkModeState(item)"
											:disabled="autoModeDisabled"
									/>
									<el-button size="small" type="danger" :icon="Delete" circle @click="moveAutoLightMode(item.modeId)" style="margin-left: 25px" :disabled="autoModeDisabled"/>
								</p>
							</el-scrollbar>
						</el-tab-pane>
					</el-tabs>
				</el-card>
				<el-card shadow="hover" style="margin-left: 65px; margin-top: 20px; width: 950px; height: 120px">
					<el-row :gutter="16">
						<el-col :span="5">
							<div class="statistic-card">
								<el-statistic
										:value="preData.preLuminance">
									<template #title>
										<div style="display: inline-flex; align-items: center">
											预设亮度
											<el-tooltip
													effect="dark"
													content="默认亮度为国家标准亮度"
													placement="top"
											>
												<el-icon style="margin-left: 4px" :size="12">
													<Warning />
												</el-icon>
											</el-tooltip>
										</div>
									</template>
								</el-statistic>
							</div>
						</el-col>
						<el-col :span="5" style="margin-left: 40px">
							<div class="statistic-card">
								<el-statistic
										:value="preData.preColorTemperature">
									<template #title>
										<div style="display: inline-flex; align-items: center">
											预设色温
											<el-tooltip
													effect="dark"
													content="默认色温为国家标准色温"
													placement="top"
											>
												<el-icon style="margin-left: 4px" :size="12">
													<Warning />
												</el-icon>
											</el-tooltip>
										</div>
									</template>
								</el-statistic>
							</div>
						</el-col>
						<el-col :span="5" style="margin-left: 40px">
							<div class="statistic-card">
								<el-statistic
										:value="actEnvironmentData.Luminance">
									<template #title>
										<div style="display: inline-flex; align-items: center">
											环境亮度
											<el-tooltip
													effect="dark"
													content="环境亮度为当前环境的实时亮度"
													placement="top"
											>
												<el-icon style="margin-left: 4px" :size="12">
													<Warning />
												</el-icon>
											</el-tooltip>
										</div>
									</template>
								</el-statistic>
							</div>
						</el-col>
						<el-col :span="5" style="margin-left: 40px">
							<div class="statistic-card">
								<el-statistic
										:value="actEnvironmentData.ColorTemperature">
									<template #title>
										<div style="display: inline-flex; align-items: center">
											环境色温
											<el-tooltip
													effect="dark"
													content="环境色温为当前环境的实时色温"
													placement="top"
											>
												<el-icon style="margin-left: 4px" :size="12">
													<Warning />
												</el-icon>
											</el-tooltip>
										</div>
									</template>
								</el-statistic>
							</div>
						</el-col>
					</el-row>
				</el-card>
				<el-card shadow="hover" style="margin-left: 65px; margin-top: 20px; width: 950px">
					<el-tag style="margin-top: 23px">预设亮度调节（单位：LX）</el-tag>
					<el-slider v-model="preLuminance" show-input size="large" max="10000" style="margin-top: 10px" :disabled="inputDisabled"/>
					<el-tag style="margin-top: 24px">预设色温调节（单位：K）</el-tag>
					<el-slider v-model="preColorTemperature" show-input size="large" max="10000" style="margin-top: 10px" :disabled="inputDisabled"/>
					<el-form-item style="margin-top: 24px">
						<el-tag style="width: 150px">使用系统默认灯光数据</el-tag>
						<el-switch
								v-model="defaultLightDate"
								class="ml-2"
								style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949; margin-left: 20px"
								@change="checkDateResource(defaultLightDate,'system')"
								:disabled="commonDisabled"
						/>
					</el-form-item>
					<el-form-item style="margin-top: 24px">
						<el-tag style="width: 150px">使用自定义灯光数据</el-tag>
						<el-switch
								v-model="autoLightDate"
								class="ml-2"
								style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949; margin-left: 20px"
								@change="checkDateResource(autoLightDate,'auto')"
								:disabled="commonDisabled"
						/>
						<el-form-item v-if="autoLightDate">
							<el-input v-model="autoModeName" placeholder="请输入自定义模式名称" style="width: 200px; margin-left: 290px"></el-input>
							<el-button type="primary" style="margin-left: 20px" @click="submitLightDate(autoModeName,preLuminance,preColorTemperature)">点击提交自定义灯光数据</el-button>
						</el-form-item>
					</el-form-item>
				</el-card>
			</el-main>
		</el-container>
	</div>
</template>

<script setup lang="ts" name="lightmodel">
import {computed, onMounted, ref} from 'vue';
import {ArrowRight, CaretBottom, SwitchButton, CaretTop, Warning, Delete} from "@element-plus/icons-vue";
import '../assets/elthirdicon/iconfont.css'
import {ElMessage, TabsPaneContext} from "element-plus";
import {isNumber} from "element-plus/es/utils";
import API from "../utils/axios";

// 控制开关
const controlSwitch = (switchState : any) => {
	changePicture(switchState);
	sendOrder();
}

const ws = new WebSocket("ws://localhost:8085/webSocket");
ws.onopen = function (event){
	console.log('建立连接');
}
ws.onclose = function (event){
	console.log('连接关闭');
}
ws.onmessage= function (event){
	// 进行弹窗提醒或其他操作
	try {
		// 将接收到的 JSON 字符串转换成 JavaScript 对象
		const message = JSON.parse(event.data);
		// 设备数据处理
		if (message.dataType == deviceValue.value){
			getEnvironmentData(message);
		}
	} catch (error) {
		console.error('JSON 解析出错', error);
	}
}
ws.onerror= function (){
	alert('websocket通信发生错误！')
};


onMounted( () => {
	// 异步获取数据
	(async () => {
		await getRoomDeviceTree();
		await getSystemLightMode();
		await getAutoLightMode();
	})()
})

// 处理环境数据
const actEnvironmentData = ref({
})
const getEnvironmentData = (message : any) => {
	// 获取更新数据
	const socketData = message.dataBody;
	const data = {
		Luminance: socketData[0].environmentLuminance,
		ColorTemperature: socketData[0].environmentColortemperature,
	}
	if (switchState.value === true){
		actEnvironmentData.value = data;
	}
	console.log(actEnvironmentData.value);
}

// 获取系统灯光模式
const getSystemLightMode = () => {
	API.post("/DeviceController/getSystemLightMode")
			.then((res) => {
				const modeData = res.data.data.map((item : any) => {
					return {
						modeId : item.id,
						mode : item.modeName,
						state: false,
						preLuminance : item.preLuminance,
						preColorTemperature : item.preColorTemperature,
					}
				})
				systemLight.value = modeData;
				console.log(systemLight);
			})
			.catch((err) => {return err})
}

// 获取自定义灯光模式
const getAutoLightMode = () => {
	API.post("/DeviceController/getAutoLightMode")
			.then((res) => {
				const modeData = res.data.data.map((item : any) => {
					return {
						modeId : item.id,
						mode : item.modeName,
						state: false,
						preLuminance : item.preLuminance,
						preColorTemperature : item.preColorTemperature,
					}
				})
				autoLight.value = modeData;
			})
			.catch((err) => {return err})
}

// 自定义模式可见性
let autoModeDisabled = ref(true)

// 系统模式可见性
let systemModeDisabled = ref(true)

// 看板数据
const boardData = ref([{preLuminance: 0, actLuminance: 0, preColorTemperature: 0, actColorTemperature: 0}])

// 通用可见性
let commonDisabled = ref(true)

// 自定义模式名称
const autoModeName = ref('')

// 人工干预灯光数据
const autoLightDate = ref(false)

// 系统默认灯光数据
const defaultLightDate = ref(false)

// 自定义灯光模式
const autoLight = ref([])

// 系统灯光模式
const systemLight = ref([])

// 色温变量
const preColorTemperature = ref(0)

// 亮度变量
const preLuminance = ref(0)

// 标签标识变量
const activeName = ref('first')

// 亮度色温可见变量
let inputDisabled = ref(true)

// 新增灯光模式数据
const addLightMode = {
	modeName: '',
	preColorTemperature: 0,
	preLuminance: 0
}
// 添加自定义灯光模式
const submitLightDate = (autoModeName : string, preLuminance : number, preColorTemperature : number) => {
	addLightMode.modeName = autoModeName;
	addLightMode.preLuminance = preLuminance;
	addLightMode.preColorTemperature = preColorTemperature;
	const modeId = ref();
	API.post("/DeviceController/addLightMode", addLightMode)
			.then((res) => {
				if (res.data.message === "自定义模式添加失败"){
					ElMessage.error(res.data.message);
				}else {
					ElMessage.success(res.data.message);
					modeId.value = res.data.data;
					autoLight.value.push({modeId : modeId, mode: autoModeName, state: false, preLuminance: preLuminance, preColorTemperature: preColorTemperature});
				}
			})
			.catch((err) => {return err})
}

// 移除自定义灯光模式
const moveAutoLightMode = (value : any) => {
	autoLight.value.map((autoMode : any) => {
		if (autoMode.modeId === value){
			if (autoMode.state === true){
				ElMessage.error("正在使用该模式，无法删除")
			}else {
				const  moveIndex = autoLight.value.findIndex((item : any) => item.modeId == value);
				const formData = new FormData();
				formData.append("modeId", value);
				API.post("/DeviceController/deleteMode", formData)
						.then((res) => {
							ElMessage.success(res.data.data);
						})
				if (moveIndex !== -1){
					autoLight.value.splice(moveIndex,1);
					if (autoLight.value.length == 0){
						systemLight.value.map((item : any) => {
							if (item.mode === '自适应模式'){
								// 开启自适应模式，同时连接接口解除原有模式绑定，绑定默认模式
								item.state = true;
								const formData = new FormData();
								formData.append("deviceNumber", deviceValue.value);
								formData.append("modeId", item.modeId);
								API.post("/DeviceController/changeMode", formData)
										.then((res) => {
											ElMessage.success(res.data.data);
										})
										.catch((err) => {return err})
								// 推送新数据到数据看板上
								preData.value = {preLuminance : item.preLuminance, preColorTemperature : item.preColorTemperature}
							}
						})
					}
				}
			}
		}
	})
}

// 切换灯光数据来源
const checkDateResource = (value : boolean, mode : string) => {
	if (mode === 'system' && value) {
		systemModeDisabled.value = false;
		autoModeDisabled.value = true;
		// 如果选择使用系统默认灯光数据，则自定义灯光数据必须关闭
		autoLightDate.value = false;
		if (value = true){
			inputDisabled.value = true;
		}
		// 关闭所有自定义模式，开启系统默认模式
		autoLight.value.map((item : any) => {
			item.state = false;
		})
		systemLight.value.map((item : any) => {
			if (item.mode === '自适应模式'){
				// 开启自适应模式，同时连接接口解除原有模式绑定，绑定默认模式
				item.state = true;
				const formData = new FormData();
				formData.append("deviceNumber", deviceValue.value);
				formData.append("modeId", item.modeId);
				API.post("/DeviceController/changeMode", formData)
						.then((res) => {
							ElMessage.success(res.data.data);
							sendOrder();
						})
						.catch((err) => {return err})
				// 推送新数据到数据看板上
				preData.value = {preLuminance : item.preLuminance, preColorTemperature : item.preColorTemperature}
			}
		})
	} else if (mode === 'auto' && value) {
		systemModeDisabled.value = true;
		autoModeDisabled.value = false;
		// 如果选择使用自定义灯光数据，则系统默认灯光数据必须关闭
		defaultLightDate.value = false;
		if (value = true){
			inputDisabled.value = false;
		}
		// 关闭所有系统模式，开启自定义默认模式
		systemLight.value.map((item : any) => {
			item.state = false;
		})
	}

	// 检查是否所有灯光数据来源都关闭了
	if (mode === 'system' && !value && autoModeDisabled.value) {
		// 如果使用系统默认灯光数据和自定义灯光数据都关闭，则默认开启使用系统默认灯光数据
		systemModeDisabled.value = false;
		autoModeDisabled.value = true;
		defaultLightDate.value = true; // 默认开启使用系统默认灯光数据
		inputDisabled.value = true; // 默认关闭输入

		// 关闭所有自定义模式，开启系统默认模式
		autoLight.value.map((item : any) => {
			item.state = false;
		});
		systemLight.value.map((item : any) => {
			if (item.mode === '自适应模式') {
				item.state = true;
				boardData.value = [{ preLuminance: item.preLuminance, preColorTemperature: item.preColorTemperature, actLuminance: 3000, actColorTemperature: 3798 }];
			}
		});
	} else if (mode === 'auto' && !value && systemModeDisabled.value) {
		// 如果使用系统默认灯光数据和自定义灯光数据都关闭，则默认开启使用系统默认灯光数据
		systemModeDisabled.value = true;
		autoModeDisabled.value = false;
		autoLightDate.value = true; // 默认开启使用自定义灯光数据
		inputDisabled.value = false; // 默认开启输入

		// 关闭所有系统模式，开启自定义默认模式
		systemLight.value.map((item : any) => {
			item.state = false;
		});
	}
}

// 检查模式开启状态
const checkModeState = (value : any) => {
	// 系统模式开关状态与数据渲染
	systemLight.value.map((item : any) =>{
		if (item.mode !== value.mode){
			item.state = false
		}
		if (item.mode === value.mode && value.state === true){
			// 添加新绑定模式
			const formData = new FormData();
			formData.append("deviceNumber", deviceValue.value);
			formData.append("modeId", item.modeId);
			API.post("/DeviceController/changeMode", formData)
					.then((res) => {
						ElMessage.success(res.data.data);
						sendOrder();
					})
					.catch((err) => {return err})
			// 推送新数据到数据看板上
			preData.value = {preLuminance : item.preLuminance, preColorTemperature : item.preColorTemperature}
		}
	})

	// 自定义模式开关状态与数据渲染
	autoLight.value.map((item : any) =>{
		if (item.mode !== value.mode){
			item.state = false
		}
		if (item.mode === value.mode && value.state === true){
			// 添加新绑定模式
			const formData = new FormData();
			formData.append("deviceNumber", deviceValue.value);
			formData.append("modeId", item.modeId);
			API.post("/DeviceController/changeMode", formData)
					.then((res) => {
						ElMessage.success(res.data.data);
						sendOrder();
					})
					.catch((err) => {return err})
			// 推送新数据到数据看板上
			preData.value = {preLuminance : item.preLuminance, preColorTemperature : item.preColorTemperature}
		}
	})

	// 检查是否所有模式都关闭了
	let allModesOff = true;
	systemLight.value.map((item : any) => {
		if (item.state === true) {
			allModesOff = false;
		}
	});
	autoLight.value.map((item : any) => {
		if (item.state === true) {
			allModesOff = false;
		}
	});
	// 如果所有模式都关闭，且没有其他模式打开，则打开系统默认的自适应模式
	if (allModesOff) {
		systemLight.value.map((item : any) => {
			if (item.mode === '自适应模式') {
				item.state = true;
				systemModeDisabled.value = false;
				autoModeDisabled.value = true;
				const formData = new FormData();
				formData.append("deviceNumber", deviceValue.value);
				formData.append("modeId", item.modeId);
				API.post("/DeviceController/changeMode", formData)
						.then((res) => {
							ElMessage.success(res.data.data);
							sendOrder();
						})
						.catch((err) => {return err})
				// 推送新数据到数据看板上
				preData.value = {preLuminance : item.preLuminance, preColorTemperature : item.preColorTemperature}
			}
		});
	}
}

const handleClick = (tab: TabsPaneContext, event: Event) => {
	console.log(tab, event)
}

// 开关灯图片地址变量
let pictureUrl = ref('src/assets/img/灭灯.png');
const preData = ref({});
// 切换开关图片
const changePicture = (switchState : boolean) => {
	if (switchState === true){
		console.log("开灯")
		pictureUrl.value = 'src/assets/img/灯.png'
		const formData = new FormData();
		formData.append("deviceNumber", deviceValue.value)
		// 获取该设备所绑定且开启的灯光模式，默认开启自适应模式
		API.post("/DeviceController/getDeviceMode", formData)
				.then((res) => {
					systemLight.value.map((item : any) => {
						if (item.modeId === res.data.data){
							item.state = true;
							inputDisabled.value = true;
							defaultLightDate.value = true;
							autoLightDate.value = false;
							systemModeDisabled.value = false;
							autoModeDisabled.value = true;
							preData.value = item;
							autoLight.value.map((autoMode : any) => {
								autoMode.state = false;
							})
						}else {
							item.state = false;
						}
					})
					autoLight.value.map((item : any) => {
						if (item.modeId === res.data.data){
							item.state = true;
							inputDisabled.value = false;
							defaultLightDate.value = false;
							autoLightDate.value = true;
							systemModeDisabled.value = true;
							autoModeDisabled.value = false;
							preData.value = item;
							systemLight.value.map((systemMode : any) => {
								systemMode.state = false;
							})
						}else {
							item.state = false;
						}
					})
				})
				.catch((err) => {return err})
		commonDisabled.value = false;
	}else{
		console.log("关灯")
		pictureUrl.value = 'src/assets/img/灭灯.png'
		commonDisabled.value = true;
		systemModeDisabled.value = true;
		autoModeDisabled.value = true;
		defaultLightDate.value = false;
		autoLightDate.value = false;
		systemLight.value.map((item : any) => {
			item.state = false;
		})
		autoLight.value.map((item : any) => {
			item.state = false;
		})
		boardData.value = [{preLuminance: 0, preColorTemperature: 0, actLuminance: 0, actColorTemperature: 0}];
	}
}

// 照明设备状态
const switchState = ref(false)
// 选择设备
const props = {
	multiple: false,
}

// 灯光控制开关可见性
let lightDisabled = ref(true)
// 获取当前操作设备
let deviceValue = ref('');
const getDevice = (value : any) => {
	deviceValue.value = value[1];
	lightDisabled.value = deviceValue.value?.length === 0;
	getDeviceStatus(value[1]);
}

// 获取教室绑定设备信息
const options = ref([])
const getRoomDeviceTree = () => {
	API.post("/DeviceController/getDeviceTree")
			.then((res) => {
				options.value = res.data.data.map((item : any) => {
					return {value : item.roomNumber, label : item.roomName,
					children : item.deviceChild.map((child : any) => {
						return {value : child.deviceNumber, label : child.deviceName}
					})}
				})
			})
}

// 获取设备状态
const getDeviceStatus = (deviceNumber : string) => {
	const formData = new FormData();
	formData.append("deviceNumber", deviceNumber)
  API.post("/DeviceController/getDeviceStatus", formData)
			.then((res) => {
				const deviceData = res.data.data.deviceWorkStatus;
				if (deviceData === 1){
					switchState.value = true;
				}else {
					switchState.value = false;
				}
				changePicture(switchState.value);
			})
			.catch((err) => {return err})
}

// 发送操控指令
// 操控指令数据
const deviceIdSet  = {
	deviceNumberSet: [],
	order: '',
}
const sendOrder = () => {
	if (deviceIdSet.deviceNumberSet.length == 1){
		deviceIdSet.deviceNumberSet.shift();
	}
	deviceIdSet.deviceNumberSet.push(deviceValue.value);
	if (switchState.value == true){
		deviceIdSet.order = 'turn_on';
	}else if (switchState.value == false){
		deviceIdSet.order = 'turn_off';
	}
	console.log(deviceIdSet);
	API.post("/DeviceController/controlDevice", deviceIdSet)
			.then((res) => {
				ElMessage(res.data.data);
			})
}
</script>

<style scoped>
.scrollbar-demo-item {
	display: flex;
	align-items: center;
	justify-content: center;
	height: 45px;
	margin: 10px;
	text-align: center;
	border-radius: 4px;
	background: var(--el-color-primary-light-9);
	color: var(--el-color-primary);
}
.icon-li-content i {
	font-size: 36px;
	color: #606266;
}
.icon-li-content span {
	margin-top: 10px;
	color: #787878;
}
.demo-tabs > .el-tabs__content {
	padding: 32px;
	color: #6b778c;
	font-size: 32px;
	font-weight: 600;
}
:global(h2#card-usage ~ .example .example-showcase) {
	background-color: var(--el-fill-color) !important;
}

.el-statistic {
	--el-statistic-content-font-size: 28px;
}

.statistic-card {
	height: 100%;
	padding: 20px;
	border-radius: 4px;
	background-color: var(--el-bg-color-overlay);
}

.statistic-footer {
	display: flex;
	justify-content: space-between;
	align-items: center;
	flex-wrap: wrap;
	font-size: 12px;
	color: var(--el-text-color-regular);
	margin-top: 16px;
}

.statistic-footer .footer-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.statistic-footer .footer-item span:last-child {
	display: inline-flex;
	align-items: center;
	margin-left: 4px;
}

.green {
	color: var(--el-color-success);
}
.red {
	color: var(--el-color-error);
}
</style>
